package com.haier.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haier.constant.Constant;
import com.haier.constant.HpConstant;
import com.haier.constant.URLConstant;
import com.haier.dto.HpAuthorizerConfigDto;
import com.haier.dto.HpGoApplyDto;
import com.haier.entity.*;
import com.haier.mapper.*;
import com.haier.service.*;
import com.haier.utils.BeanUtil;
import com.haier.utils.EmptyUtils;
import com.haier.utils.GetUtils;
import com.haier.vo.HpAuthorizerConfigVo;
import com.haier.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 授权配置
 * </p>
 *
 * @author yuandd
 * @since 2020-07-29
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class HpAuthorizerConfigServiceImpl extends ServiceImpl<HpAuthorizerConfigMapper, HpAuthorizerConfig>
		implements IHpAuthorizerConfigService {
	@Autowired
	private HpConstantMapper hpConstantMapper;
	@Autowired
	private IhaierService ihaierService;
	@Autowired
	private IHpGoApplyService iHpGoApplyService;
	@Autowired
	private HpGoApplyMapper hpGoApplyMapper;
	@Autowired
	private HpAreaMapper hpAreaMapper;
	@Autowired
	private HpGardenMapper hpGardenMapper;
	@Autowired
	private IJobService iJobService;
	@Autowired
	private HpTaskLogMapper hpTaskLogMapper;

	/**
	 * 查询列表
	 * @param dto
	 * @return
	 */
	@Override
	public IPage page(HpAuthorizerConfigDto dto) {
		Page<HpAuthorizerConfig> page = new Page<>(dto.getPageNo(), dto.getPageSize(), dto.getHasTotal());
		IPage<HpAuthorizerConfigVo> iPage = baseMapper.pageAuthorizerList(page, dto);
		return iPage;
	}

	/**
     * 保存或修改授权人等级
	 * @param dto
     * @return
     */
	@Override
	public ResponseVo saveOrUpdateAuthorizer(HpAuthorizerConfigDto dto) {
		String authorizerNum = dto.getAuthorizerNum();//授权人工号
		String passivityAuthorizerNum = dto.getPassivityAuthorizerNum();//被授权人工号
		if (EmptyUtils.isEmpty(authorizerNum)) {
			return ResponseVo.checkError("授权人工号不能为空!");
		}
		if (EmptyUtils.isEmpty(passivityAuthorizerNum)) {
			return ResponseVo.checkError("被授权人工号不能为空!");
		}
		if(authorizerNum.equals(passivityAuthorizerNum)){
			return ResponseVo.checkError("授权人和被授权人不能相同!");
		}
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("authorizer_num",authorizerNum);
		queryWrapper.eq("passivity_authorizer_num",passivityAuthorizerNum);
		queryWrapper.eq("is_enable",HpConstant.ISENABLE_YES);
		Integer integer = baseMapper.selectCount(queryWrapper);
		if(integer>0){
			return ResponseVo.checkError("已有授权人");
		}
		try {
			//获取授权人、被授权人，校验等级
			String authorizerLevel = "";//授权人等级
			String passivityAuthorizerLevel = "";//被授权人等级
			HpConstantEntity authorizerEntity = hpConstantMapper.selectById(HpConstant.CONSTANT_KEY_AUTHORIZER_LEVEL);//授权人等级
			HpConstantEntity passivityAuthorizerEntity = hpConstantMapper.selectById(HpConstant.CONSTANT_KEY_PASSIVITYAUTHORIZER_LEVEL);//被授权人等级
			if(authorizerEntity!=null){
				authorizerLevel=authorizerEntity.getHpValue();
			}
			if(passivityAuthorizerEntity!=null){
				passivityAuthorizerLevel=passivityAuthorizerEntity.getHpValue();
			}

			//根据授权人工号获取信息
			JSONObject authorizerInfo = ihaierService.getUserInfo(authorizerNum);
			if(authorizerInfo!=null){
				Integer userLevel = GetUtils.getInt(authorizerInfo.getString("userLevel"));
				if(userLevel<Integer.parseInt(authorizerLevel)){
					return ResponseVo.checkError("授权人权限不足!");
				}
				dto.setAuthorizerName(authorizerInfo.getString("userName"));
			}else{
				return ResponseVo.checkError("请输入正确的授权人工号!");
			}
			//根据被授权人工号获取授权信息
			JSONObject passivityAuthorizerInfo = ihaierService.getUserInfo(passivityAuthorizerNum);
			if(passivityAuthorizerInfo!=null){
				Integer userLevel = GetUtils.getInt(passivityAuthorizerInfo.getString("userLevel"));
				if(userLevel<Integer.parseInt(passivityAuthorizerLevel)){
					return ResponseVo.checkError("被授权人权限不足!");
				}
				dto.setPassivityAuthorizerName(passivityAuthorizerInfo.getString("userName"));
			}else{
				return ResponseVo.checkError("请输入正确的被授权人工号!");
			}
			//保存授权信息
			dto.setCreateTime(new Date());
			HpAuthorizerConfig bean = new HpAuthorizerConfig();
			BeanUtil.copyNotNullBean(dto, bean);
			if (EmptyUtils.isEmpty(dto.getId())) {
				bean.setIsEnable(HpConstant.ISENABLE_YES);
				baseMapper.insert(bean);
				//处理待办
				dealTask(authorizerNum,passivityAuthorizerInfo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseVo.checkError("授权失败！");
		}
		return ResponseVo.success();
	}

	/**
	 * 授权-处理待办
	 */
	private void dealTask (String authorizerNum,JSONObject passivityAuthorizerInfo) {
		try {
			//根据审核人查找当前该员工的待办
			QueryWrapper queryWrapper = new QueryWrapper();
			queryWrapper.eq("authorizer_Id",authorizerNum);
			queryWrapper.eq("status",HpConstant.HP_GO_APPLY_STATUS_10);
			List<HpGoApply> list = iHpGoApplyService.list(queryWrapper);
			for (int i = 0; i < list.size(); i++) {
				HpGoApply bean = list.get(i);
				//撤销
				cancleTask(bean);
				//发待办
				startTask(bean,passivityAuthorizerInfo);
			}

		}catch(Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * 取消待办
	 * @param bean
	 */
	private void cancleTask(HpGoApply bean){
		try{
			//从待办日志表根据申请单号查询日志
			QueryWrapper queryWrapper = new QueryWrapper();
			queryWrapper.eq("apply_id",bean.getId());
			queryWrapper.eq("status",HpConstant.HP_GO_APPLY_STATUS_10);
			HpTaskLog hpTaskLog = hpTaskLogMapper.selectOne(queryWrapper);
			//取消待办
			List<String> taskIdList = new ArrayList<String>();
			taskIdList.add(hpTaskLog.getTaskId());
			iJobService.complete(taskIdList, bean.getAuditor(), HpConstant.HP_GO_APPLY_STATUS_F20);
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * 发起待办
	 * @param bean
	 */
	private void startTask(HpGoApply bean,JSONObject passivityAuthorizerInfo){
		try {
			String auditor=passivityAuthorizerInfo.getString("userId");//被授权人
			String name=passivityAuthorizerInfo.getString("userName");//被授权人
			//发待办
			Long id = bean.getId();
			StringBuffer title = new StringBuffer();
			HpArea hpArea = hpAreaMapper.selectById(bean.getAreaId());
			HpGarden hpGarden = hpGardenMapper.selectById(hpArea.getGardenId());
			title.append("[HiPass] 待审核：").append(bean.getName()).append(bean.getJobNumber());
			title.append(" 申请 ").append(bean.getDateDay()).append(" 通行").append(hpGarden.getName()).append("-")
					.append(hpArea.getName());
			String taskId = Constant.JOB_SYSID + "_" + GetUtils.getIntString(GetUtils.getInt(id), 10);
			iJobService.begin(taskId, bean.getJobNumber(), auditor, title.toString(), id);

 			//修改申请的审核人
			bean.setAuditor(auditor);
			bean.setAuditorName(name);
			hpGoApplyMapper.updateById(bean);
		}catch (Exception e){
			e.printStackTrace();
		}
	}


	/**
	 * 撤销授权
	 * @param dto
	 * @return
	 */
	@Override
	public Object cancleAuthorizer(HpAuthorizerConfigDto dto) {
		String authorizerNum = dto.getAuthorizerNum();//授权人工号
		try {
			//根据授权人、被授权人查询
			QueryWrapper queryWrapper = new QueryWrapper();
			queryWrapper.eq("authorizer_num",authorizerNum);
			queryWrapper.eq("is_enable",HpConstant.ISENABLE_YES);
			HpAuthorizerConfig hpAuthorizerConfig = baseMapper.selectOne(queryWrapper);
			if(hpAuthorizerConfig!=null){
				hpAuthorizerConfig.setIsEnable(HpConstant.ISENABLE_NO);
				hpAuthorizerConfig.setUpdateUserid(dto.getCreateUserid());
				hpAuthorizerConfig.setUpdateUser(dto.getCreateUser());
				hpAuthorizerConfig.setUpdateTime(new Date());
				baseMapper.updateById(hpAuthorizerConfig);
				//根据授权人工号获取信息
				JSONObject authorizerInfo = ihaierService.getUserInfo(authorizerNum);
				//处理待办
				dealTaskCancleAuthorizer(authorizerNum,authorizerInfo);
  			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseVo.checkError("撤销授权失败！");
		}
		return ResponseVo.success();
	}

	/**
	 * 撤销授权-处理待办
	 */
	private void dealTaskCancleAuthorizer (String authorizerNum,JSONObject authorizerInfo) {
		try {
			//根据审核人查找当前该员工的待办
			QueryWrapper queryWrapper = new QueryWrapper();
			queryWrapper.eq("authorizer_Id",authorizerNum);
			queryWrapper.eq("status",HpConstant.HP_GO_APPLY_STATUS_10);
			List<HpGoApply> list = iHpGoApplyService.list(queryWrapper);
			for (int i = 0; i < list.size(); i++) {
				HpGoApply bean = list.get(i);
				//撤销
				cancleTask(bean);
				//发待办
				startTaskToAuthorizer(bean,authorizerInfo);
			}

		}catch(Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * 发起待办
	 * @param bean
	 */
	private void startTaskToAuthorizer(HpGoApply bean,JSONObject authorizerInfo) {
		try {
			String auditor = authorizerInfo.getString("userId");//授权人
			String name = authorizerInfo.getString("userName");//授权人
			//发待办
			Long id = bean.getId();
			StringBuffer title = new StringBuffer();
			HpArea hpArea = hpAreaMapper.selectById(bean.getAreaId());
			HpGarden hpGarden = hpGardenMapper.selectById(hpArea.getGardenId());
			title.append("[HiPass] 待审核：").append(bean.getName()).append(bean.getJobNumber());
			title.append(" 申请 ").append(bean.getDateDay()).append(" 通行").append(hpGarden.getName()).append("-")
					.append(hpArea.getName());
			String taskId = Constant.JOB_SYSID + "_" + GetUtils.getIntString(GetUtils.getInt(id), 10);
			iJobService.begin(taskId, bean.getJobNumber(), auditor, title.toString(), id);

			//修改申请的审核人
			bean.setAuditor(auditor);
			bean.setAuditorName(name);
			hpGoApplyMapper.updateById(bean);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
